<?php
/**
 * Bdat Site development
 * @author Will Skates
 */

/*----------------------------------------------------------------------------------------------------*/

/**
 * Outline of properties and functionality required to make and use content in the system which is used 
 * to populate masonry blocks. In this resource information blocks.
 * @author Will Skates
 */
require_once('blockmodel.php');

class Resource extends BlockModel {
	
	//Define where we can find resource data in the database.
	public $ctable = 'resources';
	
	/**
	 * Define parameters which dictate how the thumbnail images will be written.
	 * @var Array
	 */
	public $imageSizes = array(
		'blockThumb'=>array(
			'width'=>'190',
			'height'=>'200'
		)
	);
	
	/*----------------------------------------------------------------------------------------------------*/
	
	/**
	 * Construct an sql query to get the data for events from the database. (This version of the function includes image data).
	 * @see BlockModel::getQuery()
	 */
	public function getQuery(  )
	{
		return 'SELECT ' . $this->ctable . '.uid,
						title,
						content,
						image,
						imageExtension,
						user_profiles.name,
						user_profiles.link,
						gradyears.date AS gradyear,
						sticky FROM ' . $this->ctable . ' 
				LEFT JOIN user_profiles ON user_profiles.userid = ' . $this->ctable . '.author
				LEFT JOIN gradyears ON gradyears.uid = user_profiles.gradyear
				WHERE published = 1';
	}
	
	/*----------------------------------------------------------------------------------------------------*/
	
	/**
	 * Gets image data from the post when it is saved in the cms so that it can be used to generate a thumbnail image.
	 * @see BlockModel::saveCallback()
	 */
	public function saveCallback()
	{
		
		parent::saveCallback();
		
		//Load in helpers for getting information from url's and writing to the file system.
		$this->load->helper('curl');
		$this->load->helper('file');
		
		//Get an image from the content of the post.
		$image = $this->fetchImage($this->content);
		if ( substr($image,-1) == '/' ) { $image = substr($image, 0, strlen($image)-2 ); }
		//Get the file name of the image seperately.
		$filename = end(explode('/',$image));
		
		//Get the bitmap data from the image remotely.
		$data = curlGetFile($image);
		
		//Define a location where the image can be stored on the server.
		define('DSW',DIRECTORY_SEPARATOR);
    	$path = str_replace('application' . DSW . 'models','public' . DSW . 'uploads',dirname(__FILE__));
		
		//Put the bitmap data from that file into that location on disk.
		$success = file_put_contents($path . $filename,$data);
		
		//If it was written sucessfully.	
		if ( $success ) {
			
			//Grab the filename and the extension seperately (this is because we are going to but a suffix in between the two).
			$extension = end(explode('.',$filename));
			$filename  = reset(explode('.',$filename));
			
			//Set that data in the database.
			$sql = 'UPDATE ' . $this->ctable . ' SET image=\'' . $filename . '\', imageExtension=\'' . $extension . '\' WHERE uid=' . $this->uid;
			$this->db->query($sql);
			
			//Setup the codeignighter image library configuration.
			$config = array();
			$config['image_library'] = 'gd2';
			$config['create_thumb'] = TRUE;
			$config['maintain_ratio'] = TRUE;
			
			foreach ( $this->imageSizes as $key=>$size ) {
				
				//Define the width and height of the new image.
				$config['width'] = $size['width'];
				$config['height'] = $size['height'];
				$config['source_image'] = $path . $filename . '.' . $extension;
				$config['new_image'] = $path . $filename . '-' . $key .'.' . $extension;
				
				//Resize it and save.
				$this->load->library('image_lib',$config);
				$this->image_lib->resize();
				
			}
			
		}
		
	}
	
	/*----------------------------------------------------------------------------------------------------*/
	
	/**
	 * Use regex to find the location of an image url from a string of text.
	 * @param	String	$str	- The string of text in which to search.
	 * @return 	String	$str	- The url to the image.
	 */
	private function fetchImage($str) {
		
		$imgs;
		
		$image = '';
		
		preg_match_all("/<(img|IMG).*?(SRC|src)=\"(.*?)\"/",$str,$imgs);
			
		if(sizeof($imgs[3]) > 0) {
			$image = $this->fixEnteredText($imgs[3][0]);
		}
		
		if($image != "" || !is_null($image)) {
			
			//Check that this url is valid.
			if($this->isImageUrl($image) == false) {
				$image = "";
			}
			
			//Check that a this url actually exists. (see curl helper.)
			if(fileExistsAtUrl($image) == false) {
				$image = "";
			}
		}
		
		return $image;
		
		
	}
	
	/*----------------------------------------------------------------------------------------------------*/
	
	/**
	 * Check to make sure that there is an image extension in the url that has been found.
	 * @param	String	$str	- The url to the image.
	 */
	private function isImageUrl($str) {
		
		$types = array("jpg","jpeg","png","gif");
		return in_array( end(explode('.',$str)), $types  );
	}
	
	/*----------------------------------------------------------------------------------------------------*/
	
	/**
	 * Parse any html that is in the image url to make sure that there are no additional scripts being passed with it.
	 * @param 	String	$str	- The url to check.
	 * @return 	String	$str	- The parsed text.
	 */
	private function fixEnteredText($str) {
		
		return htmlspecialchars(stripslashes(trim($str)),ENT_QUOTES);
		
	}
	
	/*----------------------------------------------------------------------------------------------------*/
	
}